using NICWebApi.Extensions.Http.Middlewares;
using NICWebApi.Extensions.Http.Options;

namespace Microsoft.Extensions.DependencyInjection;

/// <summary>
/// HTTP中间件扩展
/// </summary>
public static class HttpMiddlewareExtensions
{
    /// <summary>
    /// 使用HTTP上下文信息中间件
    /// </summary>
    /// <param name="app">应用程序构建器</param>
    /// <returns>应用程序构建器</returns>
    public static IApplicationBuilder UseHttpContextInfo(this IApplicationBuilder app)
    {
        if (app == null)
        {
            throw new ArgumentNullException(nameof(app));
        }

        return app.UseMiddleware<HttpContextInfoMiddleware>();
    }

    /// <summary>
    /// 使用HTTP上下文信息中间件
    /// </summary>
    /// <param name="app">应用程序构建器</param>
    /// <param name="configureOptions">配置选项</param>
    /// <returns>应用程序构建器</returns>
    public static IApplicationBuilder UseHttpContextInfo(
        this IApplicationBuilder app,
        Action<HttpOptions> configureOptions)
    {
        if (app == null)
        {
            throw new ArgumentNullException(nameof(app));
        }

        if (configureOptions == null)
        {
            throw new ArgumentNullException(nameof(configureOptions));
        }

        // 获取选项
        var options = Utils.GetOptions();

        // 配置选项
        configureOptions(options);

        return app.UseMiddleware<HttpContextInfoMiddleware>();
    }

    /// <summary>
    /// 添加HTTP工具
    /// </summary>
    /// <param name="services">服务集合</param>
    /// <returns>服务集合</returns>
    public static IServiceCollection AddHttpUtils(this IServiceCollection services)
    {
        if (services == null)
        {
            throw new ArgumentNullException(nameof(services));
        }

        // 添加HttpContextAccessor
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

        // 注册HTTP上下文工具
        services.AddSingleton<IHttpContextUtils, HttpContextUtils>();

        // 注册HTTP选项
        services.AddOptions<HttpOptions>();

        return services;
    }

    /// <summary>
    /// 添加HTTP工具
    /// </summary>
    /// <param name="services">服务集合</param>
    /// <param name="configureOptions">配置选项</param>
    /// <returns>服务集合</returns>
    public static IServiceCollection AddHttpUtils(
        this IServiceCollection services,
        Action<HttpOptions> configureOptions)
    {
        if (services == null)
        {
            throw new ArgumentNullException(nameof(services));
        }

        if (configureOptions == null)
        {
            throw new ArgumentNullException(nameof(configureOptions));
        }

        // 添加HttpContextAccessor
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

        // 注册HTTP上下文工具
        services.AddSingleton<IHttpContextUtils, HttpContextUtils>();

        // 注册并配置HTTP选项
        services.Configure(configureOptions);

        return services;
    }
}